import { LinkComponent } from './LinkComponent.js'
import { MessageBox } from 'element-ui'
import ReasonsOfCloseSwitch from './reasonsOfCloseSwitch'
import store from '@/store'
import { setBotSwitch, submitCloseMessageReasonsApi } from '@/api/new'

export default {
  components: { ReasonsOfCloseSwitch },
  data() {
    return {}
  },
  methods: {
    changeSwitch(e, item, type, fromSwitch) {
      if (!e && (type === 'alert' || type === 'escalation')) {
        let _self = this
        const h = _self.$createElement
        const str = `reasons-form${new Date().getTime()}`
        MessageBox({
          title: 'Tips',
          message: h(ReasonsOfCloseSwitch, { ref: str }, null),
          showCancelButton: true,
          confirmButtonText: 'Confirm',
          cancelButtonText: 'Cancel',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true
              const params = {
                ..._self.$refs[str].getDataForm(),
                botId: item.id,
                type: type,
                creator: store.state.user.id
              }
              submitCloseMessageReasonsApi(params)
              instance.confirmButtonLoading = false
              _self.startChangeSwitch(e, item, type, fromSwitch)
              done()
            } else {
              _self.switchRecovery(item, type)

              done()
            }
          }
        }).then(() => {
          this.$refs[str].clearData()
        })
      } else {
        this.startChangeSwitch(e, item, type, fromSwitch)
      }
    },
    startChangeSwitch(e, item, type, fromSwitch) {
      if (type === 'enable') {
        item.cardEnableLoading = true
      }
      if (type === 'alert') {
        item.cardAlertLoading = true
      }
      if (type === 'escalation') {
        item.cardEscalationLoading = true
      }
      if (item.version === '1') {
        this.chooseChangeSwitch(e, item, type)
        return false
      }
      this.loading = true
      if (localStorage.getItem('botview') === 'Grid') {
      } else if (localStorage.getItem('botview') === 'List') {
        if (type === 'enable') {
          item.enableLoading = true
        }
        if (type === 'alert') item.alertLoading = true
        if (type === 'escalation') item.escalationLoading = true
      }

      let enable = Boolean(item.enable)
      let alert = Boolean(item.alert)
      let escalation = Boolean(item.escalation)
      if (!e) {
        switch (type) {
          case 'enable':
            alert = false
            escalation = false
            this.$set(item, 'escalation', false)
            this.$set(item, 'alert', false)
            break
          case 'alert':
            escalation = false
            this.$set(item, 'escalation', false)
            break
          default:
            break
        }
      }

      const params = {
        enable: enable,
        alert: alert,
        escalation: escalation,
        mode: type,
        tenantLog: {
          operationGroup: 0,
          operationType: 1,
          operation: {
            enable: enable,
            alert: alert,
            escalation: escalation,
            mode: type
          }
        }
      }
      setBotSwitch({ ...params, id: item.id })
        .then(({ data: res }) => {
          if (localStorage.getItem('botview') === 'Grid') {
          } else if (localStorage.getItem('botview') === 'List') {
            if (type === 'enable') item.enableLoading = false
            if (type === 'alert') item.alertLoading = false
            if (type === 'escalation') item.escalationLoading = false
          }
          if (res.code !== 0) {
            this.dataList = []
            this.total = 0
            if (res.code === 418 || res.code === 523) {
              this.loadingCancel(item)
              this.switchRecovery(item, type)
              if (type === 'enable') item.enableLoading = false
              if (type === 'alert') item.alertLoading = false
              if (type === 'escalation') item.escalationLoading = false

              this.$emit('open-pay')
              return
            } else if (res.code === 518) {
              this.loadingCancel(item)
              this.switchRecovery(item, type)
              if (type === 'enable') item.enableLoading = false
              if (type === 'alert') item.alertLoading = false
              if (type === 'escalation') item.escalationLoading = false
              this.showNotice = true
            } else {
              this.$message.error(res.msg)
              return
            }
          }
          if (type === 'enable' && params.enable === false) {
            this.clearBot(item.id)
          }
          if (type === 'enable' && res.code === 518) {
            this.$message.error(res.msg)
          } else {
            this.$message.success(res.msg)
          }
          store.state.app.contentIsNeedRefreshCache = true
          try {
            LinkComponent.$emit('changeSwitchHanderInfo')
          } catch (error) {}
          if (localStorage.getItem('botview') === 'Grid') {
            LinkComponent.$emit('changeSwitchHanderForGrid', item, params)
          } else {
            if (fromSwitch) {
              LinkComponent.$emit('changeSwitchHanderForList')
            }
          }

          this.loadingCancel(item)
        })
        .catch(e => {
          this.loadingCancel(item)
          this.switchRecovery(item, type)
          if (localStorage.getItem('botview') === 'Grid') {
          } else if (localStorage.getItem('botview') === 'List') {
            if (type === 'enable') item.enableLoading = false
            if (type === 'alert') item.alertLoading = false
            if (type === 'escalation') item.escalationLoading = false
          }
        })
    },
    async clearBot(botId) {
      try {
        const { closeBot } = this.$interface.pay
        const params = {
          botId
        }
        await closeBot(params)
      } catch (error) {
      } finally {
      }
    },
    chooseChangeSwitch(e, item, type) {
      switch (type) {
        case 'enable':
          this.changeSwitchEnable(e, item, type)
          break
        case 'alert':
          this.changeSwitchSend(e, item, type)
          break
        case 'escalation':
          this.changeSwitchEscalation(e, item, type)
          break
        default:
          break
      }
    },
    changeSwitchEnable(e, item, type) {
      this.loading = true
      const itemMessage = item.paramsValue
      let enable = item.enable
      let send = item.send
      let sendEscalation = item.sendEscalation
      if (type === 'enable') {
        send = false
        sendEscalation = false
      }
      const params = {
        id: item.id,
        enable: enable,
        paramsValue: {
          ...itemMessage,
          send: send,
          sendEscalation: sendEscalation
        }
      }
      this.$interface.bots
        .updateTenantScriptSwitchApi(params)
        .then(({ data: res }) => {
          this.loading = false
          if (res.code !== 0) {
            this.dataList = []
            this.total = 0
            return this.$message.error(res.msg)
          }
          if (type === 'enable' && params.enable === false) {
            this.clearBot(item.id)
          }
          this.$message.success(res.msg)
          if (localStorage.getItem('botview') === 'Grid') {
            LinkComponent.$emit('changeSwitchHanderForGrid', item, params)
          } else {
            LinkComponent.$emit('changeSwitchHanderForList')
          }
          this.loadingCancel(item)
          //    LinkComponent.$emit('initPageList')
        })
        .catch(() => {
          this.loadingCancel(item)
          this.$data.data.enable = !this.$data.data.enable
          this.loading = false
        })
    },
    changeSwitchSend(e, item, type) {
      this.loading = true
      const itemMessage = item.paramsValue
      let enable = item.enable
      let send = e
      let sendEscalation = item.escalation
      if (type === 'alert') {
        sendEscalation = false
      }
      const params = {
        id: item.id,
        enable: enable,
        paramsValue: {
          ...itemMessage,
          send: send,
          sendEscalation: sendEscalation
        }
      }
      this.$interface.bots
        .updateTenantScriptSwitchApi(params)
        .then(({ data: res }) => {
          this.loading = false
          if (res.code !== 0) {
            this.dataList = []
            this.total = 0
            return this.$message.error(res.msg)
          }
          this.$message.success(res.msg)
          if (localStorage.getItem('botview') === 'Grid') {
            LinkComponent.$emit('changeSwitchHanderForGrid', item, params)
          } else {
            LinkComponent.$emit('changeSwitchHanderForList')
          }
          this.loadingCancel(item)
        })
        .catch(() => {
          this.switchRecovery(item, type)
          this.loadingCancel(item)
          this.loading = false
        })
    },
    changeSwitchEscalation(e, item, type) {
      this.loading = true
      const itemMessage = item.paramsValue
      let enable = item.enable
      let send = item.alert
      let sendEscalation = e

      const params = {
        id: item.id,
        enable: enable,
        paramsValue: {
          ...itemMessage,
          send: send,
          sendEscalation: sendEscalation
        }
      }
      this.$interface.bots
        .updateTenantScriptSwitchApi(params)
        .then(({ data: res }) => {
          this.loading = false
          if (res.code !== 0) {
            this.dataList = []
            this.total = 0
            return this.$message.error(res.msg)
          }
          this.$message.success(res.msg)
          if (localStorage.getItem('botview') === 'Grid') {
            LinkComponent.$emit('changeSwitchHanderForGrid', item, params)
          } else {
            LinkComponent.$emit('changeSwitchHanderForList')
          }
          this.loadingCancel(item)
        })
        .catch(() => {
          this.switchRecovery(item, type)
          this.loadingCancel(item)
          this.loading = false
        })
    },
    switchRecovery(item, type) {
      this.$nextTick(() => {
        item[type] = !item[type]
      })
    },
    loadingCancel(item) {
      item.cardEnableLoading = false
      item.cardAlertLoading = false
      item.cardEscalationLoading = false
      this.$forceUpdate()
    }
  }
}
